/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-var-requires */

const fs = require('fs');
const sharp = require('sharp');
const Path = require('path');

fs.readdir('./mt/', (err, files) => {
  if (err) {
    console.log('?????', err);
  } else {

    for (let i = 0; i < files?.length; i++) {
      if (files[i] === '.DS_Store') {
        console.log(1);
      } else {
        readParame(Path.join('./mt/', files[i]));
      }
    }
  }
});

function readParame(filesPath, size = 400) {
  return new Promise(async (resolve) => {
    try {
      console.log('filesPath:', filesPath);

      const metadata = await sharp(filesPath).metadata();
      console.log('metadata:', metadata);
      const ratio = metadata.width / metadata.height; // 获取宽高比
      const width = size;
      const height = parseInt(width / ratio + '');
      await sharp(filesPath)
        .resize({
          width,
          height,
        })
        .extract({ width: width - 160, height: height - 40, left: 80, top: 20 }) //四周去边
        .toBuffer()
        .then(async (buffer) => {
          const dir = Path.dirname(filesPath);
          console.log('dir', dir);
          const ext = Path.extname(filesPath);
          const name = Path.basename(filesPath);
          const newPath = `cop/${name.split('.')[0]}_${size}${ext}`;
          await fs.writeFileSync(newPath, buffer);
          resolve({
            filePath: newPath,
            fileName: `${name.split('.')[0]}_${size}${ext}`,
          });
        });
    } catch (error) {
      console.log(`An error occurred during processing: ${error}`);
    }
  });
}
